#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GPU服务器统一配置
支持环境变量，适配镜像部署
"""

import os
import socket
from typing import Optional, Dict

class Config:
    """GPU服务器配置类"""
    
    # ==================== 网络配置（自动检测） ====================
    
    @staticmethod
    def get_internal_ip() -> str:
        """自动检测内网IP"""
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except Exception:
            return "127.0.0.1"
    
    @staticmethod
    def detect_region(internal_ip: str) -> str:
        """根据内网IP自动检测地域"""
        REGION_MAP = {
            'ap-beijing': ['10.2.', '10.5.', '10.6.'],
            'ap-shanghai': ['10.3.'],
            'ap-guangzhou': ['10.1.'],
            'ap-chengdu': ['10.4.']
        }
        for region, prefixes in REGION_MAP.items():
            for prefix in prefixes:
                if internal_ip.startswith(prefix):
                    return region
        return 'ap-beijing'  # 默认北京
    
    # 自动检测的值
    INTERNAL_IP: str = get_internal_ip.__func__()
    REGION: str = detect_region.__func__(INTERNAL_IP)
    
    # 公网IP（优先从环境变量，否则通过API获取，镜像实例会自动更新）
    PUBLIC_IP: Optional[str] = os.getenv('GPU_SERVER_PUBLIC_IP')
    
    # ==================== API网关配置 ====================
    
    # C服务器网关地址（镜像实例统一使用域名）
    GATEWAY_URL: str = os.getenv('API_GATEWAY_URL', 'https://www.gongjuxiang.work')
    
    # Webhook密码
    WEBHOOK_SECRET: str = os.getenv(
        'WEBHOOK_SECRET', 
        'gpu-server-register-to-api-gateway-2024'
    )
    
    # ==================== GPU服务器配置 ====================
    
    SERVER_PORT: int = 8000
    WORKER_COUNT: int = 1  # GPU服务器单worker（避免显存冲突）
    MAX_CONTENT_LENGTH: int = 100 * 1024 * 1024  # 100MB
    
    # ==================== 腾讯云COS配置 ====================
    
    COS_SECRET_ID: str = os.getenv('COS_SECRET_ID', '')
    COS_SECRET_KEY: str = os.getenv('COS_SECRET_KEY', '')
    COS_BUCKET_PREFIX: str = os.getenv('COS_BUCKET_PREFIX', 'photoenhancei')
    COS_ACCOUNT_ID: str = os.getenv('COS_ACCOUNT_ID', '1259206939')
    COS_REGION: str = REGION  # 使用自动检测的地域
    CDN_DOMAIN: str = os.getenv('CDN_DOMAIN', 'cdn.gongjuxiang.work')
    
    @classmethod
    def get_cos_bucket_name(cls) -> str:
        """生成COS bucket名称"""
        return f"{cls.COS_BUCKET_PREFIX}-{cls.COS_ACCOUNT_ID}"
    
    # ==================== 文件路径配置 ====================
    
    UPLOAD_FOLDER: str = '/tmp/gpu-uploads'
    RESULT_FOLDER: str = '/tmp/gpu-results'
    LOG_FOLDER: str = '/home/ubuntu/gpu-server/logs'
    
    # ==================== GFPGAN模型配置 ====================
    
    GFPGAN_MODEL_PATH: str = os.getenv(
        'GFPGAN_MODEL_PATH',
        '/home/ubuntu/models/gfpgan'
    )
    
    TILE_SIZE: int = 400
    
    QUALITY_LEVELS: Dict[str, float] = {
        'low': 0.5,
        'medium': 0.7,
        'high': 1.0
    }
    
    # ==================== 图片清理配置 ⭐ ====================
    
    CLEANUP_ENABLED: bool = True  # 是否启用自动清理
    CLEANUP_INTERVAL: int = 3600  # 定时清理间隔（秒），默认1小时
    CLEANUP_AGE: int = 3600  # 清理超过多少秒的文件，默认1小时
    IMMEDIATE_CLEANUP: bool = True  # 任务完成后立即清理
    
    # ==================== 日志配置 ====================
    
    LOG_LEVEL: str = os.getenv('LOG_LEVEL', 'INFO')
    LOG_FORMAT: str = '[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'
    
    @classmethod
    def init_folders(cls):
        """初始化必要的文件夹"""
        import os
        os.makedirs(cls.UPLOAD_FOLDER, exist_ok=True)
        os.makedirs(cls.RESULT_FOLDER, exist_ok=True)
        os.makedirs(cls.LOG_FOLDER, exist_ok=True)
    
    @classmethod
    def cleanup_temp_folders(cls):
        """清空临时文件夹（启动时调用）"""
        import shutil
        for folder in [cls.UPLOAD_FOLDER, cls.RESULT_FOLDER]:
            if os.path.exists(folder):
                shutil.rmtree(folder)
            os.makedirs(folder, exist_ok=True)
    
    @classmethod
    def print_config(cls):
        """打印当前配置（用于调试）"""
        print("=" * 60)
        print("GPU服务器配置信息")
        print("=" * 60)
        print(f"内网IP: {cls.INTERNAL_IP}")
        print(f"公网IP: {cls.PUBLIC_IP or '未设置（将自动获取）'}")
        print(f"地域: {cls.REGION}")
        print(f"网关URL: {cls.GATEWAY_URL}")
        print(f"服务端口: {cls.SERVER_PORT}")
        print(f"COS Bucket: {cls.get_cos_bucket_name()}")
        print(f"COS地域: {cls.COS_REGION}")
        print(f"CDN域名: {cls.CDN_DOMAIN}")
        print(f"模型路径: {cls.GFPGAN_MODEL_PATH}")
        print(f"清理配置: 启用={cls.CLEANUP_ENABLED}, 间隔={cls.CLEANUP_INTERVAL}秒")
        print("=" * 60)

